{% extends "base.html" %}

{% block title %}Deployments{% endblock %}

{% block head %}
{{ super() }}
<!-- DataTables -->
<link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
<!-- bootstrap-select -->
<link rel="stylesheet" href="/static/css/bootstrap-select.min.css">
{% endblock %}

{% block content %}
<!-- 页面头 -->
<section class="content-header">
  <!--头部标题-->
  <h1>
    Deployments
    <!--    <small>advanced tables</small>-->
  </h1>
  <!--面包屑-->
  <ol class="breadcrumb">
    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
    <li><a href="/blues/blues/clusterler/cluster">集群管理</a></li>
    <li class="active"><a href="/blues/cluster/deployments/">Deployments</a></li>
  </ol>
</section>


<!-- 页面内容 -->
<section class="content">
  <div class="row">

    <div class="col-xs-12">
      <!--    顶部工具栏-->
      <form class="form-inline" style="margin-bottom: 10px">
        <div class="form-group">
          <label for="selectCluster"> <span style="color: red">*</span> 集群</label>
          <select class="form-control need-refresh-table" id="selectCluster" name="cluster_id" required>
            <option value="" selected>--请选择--</option>
          </select>
        </div>
        &nbsp;
        <div class="form-group">
          <label for="selectNamespace"> <span style="color: red">*</span> 命名空间</label>
          <select class="form-control need-refresh-table" id="selectNamespace" name="namespace" required>
            <!--            <option value="_all" selected>ALL</option>-->
          </select>
        </div>
        &nbsp;
      </form>


      <!--表格1-->
      <div class="box ">
        <!--        <div class="box-header">-->
        <!--          <h3 class="box-title">节点概览</h3>-->
        <!--        </div>-->
        <div class="box-body">
          <table id="example1" class="table-hover table-bordered table-condensed table-striped" style="width:100%;font-size: 90%">
            <thead>
            <tr>
              <th>名称</th>
              <th>命名空间</th>
              <th>Pods</th>
              <th>状态</th>
              <th>镜像</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody id="tbody">
            </tbody>
          </table>
        </div>
        <!-- /.box-body -->
        <!-- Loading (remove the following to stop the loading)-->
        <div id="loading" class="overlay" style="display: block">
          <i class="fa fa-refresh fa-spin"></i>
        </div>
        <!-- end loading -->
      </div>
      <!-- /.box -->

    </div>
    <!-- /.col -->
  </div>
  <!-- /.row -->
</section>
<!-- /.页面内容 -->
{% endblock %}


{% block script %}
<script src="/static/js/bootstrap-select.min.js"></script>
<!-- DataTables -->
<script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- Page specific script -->
<script type="text/javascript">
    // 解析URL, 定义全局变量
    var type = 'deployments'
    var cluster_id = getQueryString("cluster_id")
    var namespace = getQueryString("namespace")

    console.log(cluster_id, namespace)


    // 检测本地是否保存变量
    if (cluster_id > 0) {
        console.log("save cluster_id to session_storage")
        sessionStorage.setItem("cluster_id", cluster_id)
    } else {
        cluster_id = sessionStorage.getItem("cluster_id")
        // 设置cluster_id默认值
        if (cluster_id == null) {
            cluster_id = 1
            sessionStorage.setItem("cluster_id", cluster_id)
        }
    }
    if (namespace) {
        sessionStorage.setItem("namespace", namespace)
    } else {
        namespace = sessionStorage.getItem("namespace")
        // 设置默认值
        if (namespace == null) {
            namespace = '_all'
            sessionStorage.setItem("namespace", namespace)
        }
    }


    // 页面载入完毕后执行接口调用
    $(document).ready(function () {
        // $('#loading').hide()
        // 获取所有集群列表，并填入下拉菜单
        $.get('/api/cluster_list', function (data) {
            var clusters = data
            console.log(data)
            for (let i in clusters) {
                $('#selectCluster').append('<option value="' + clusters[i].id + '">' + clusters[i].name + '</option>')
            }
            // 如果url带cluster_id，则刷新namespace下拉菜单
            if (cluster_id > 0) {
                console.log("URL have cluster_id")
                $('#selectCluster').val(cluster_id)
                refreshNamespace(cluster_id)

                // 如果url带namespace，则刷新资源下拉菜单，刷新数据表格
                if (namespace) {
                    console.log("URL have namespace")
                    $('#selectNamespace').val(namespace)
                    refreshTable(cluster_id, namespace, type)
                }
            }
        })
    })

    function refreshTable(cluster_id, namespace, type) {
        $('#loading').show()
        // 数据有效性校验
        if (cluster_id === '' || namespace === '' || type === '') {
            bootbox.alert("有未填写的参数，请返回检查")
            return false
        }
        //接口调用，并填充数据Table
        let url = '/api/cluster/' + cluster_id + '/' + namespace + '/' + type + '/'
        $.get(url, function (result) {
            console.log(result)
            $('#tbody').find('td').remove()

            // 不指定资源名查询，返回list
            for (let i in result.items) {
                let labels = result.items[i].spec.selector.matchLabels
                // console.log("raw labels", labels)
                let name = result.items[i].metadata.name
                let resource_ns = result.items[i].metadata.namespace
                let ready = 0
                if (result.items[i].status.readyReplicas) {
                    ready = result.items[i].status.readyReplicas
                }
                let replicas = result.items[i].status.replicas
                let status = '<i class="fa fa-check-circle" style="color: forestgreen"></i>'
                if (ready === 0) {
                    status = '<i class="fa fa-warning" style="color: red"></i>'
                }

                // let k = Object.keys(labels)[0]
                // let v = labels[k]
                // let selector = k + '=' + v
                let selector = ''
                for (let i in labels) {
                    // console.log(i)
                    let k = i
                    let v = labels[k]
                    selector += k + '=' + v + ','
                }
                selector = selector.slice(0, -1)  // 删除最后一位的,
                // console.log(selector)

                let url_pods = '/cluster/' + cluster_id + '/' + resource_ns + '/' + type + '/' + name + '/pods/?selector=' + selector
                let url_yml = '/cluster/' + cluster_id + '/' + resource_ns + '/' + type + '/' + name + '/yaml'
                let url_svc = '/cluster/services/?cluster_id=' + cluster_id + "&namespace=" + resource_ns + '&name=' + name
                var text = '<tr>'
                text += '<td>' + result.items[i].metadata.name + '</td>'
                text += '<td>' + resource_ns + '</td>'
                text += '<td>' + ready + '/' + replicas + '</td>'
                text += '<td>' + status + '</td>'
                text += '<td>' + result.items[i].spec.template.spec.containers[0]['image'] + '</td>'
                text += '<td>' + result.items[i].metadata.creationTimestamp + '</td>'
                // text += '<td>' + JSON.stringify(result.items[i].spec.selector.matchLabels) + '</td>'

                text += '<td><div class="btn-group">' +
                    '<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><i class="fa fa-ellipsis-v"></i></button>' +
                    '<ul class="dropdown-menu" role="menu">' +
                    `<li><a href="${url_pods}">Pod</a></li>` +
                    `<li><a href="${url_svc}">Service</a></li>` +
                    `<li><a href="${url_yml}">编辑</a></li>` +
                    `<li><a href="javascript:void(0)" class="btn_restart">重置</a></li>` +
                    '</ul></div></td>'

                text += '</tr>'
                $('#tbody').append(text)
            }


            $('#example1').DataTable({
                language: {
                    "url": "/static/language.json"
                },
                processing: true,
                paging: true,
                lengthChange: true,
                searching: true,
                ordering: true,
                order: [[1, 'asc'], [0, 'asc']],
                autoWidth: true,
                responsive: true,
            });

            $('#loading').hide()
        });
    }

    function refreshNamespace(cluster_id) {
        console.log("refresh namespace");
        // var current_cluster_id = $('#selectCluster').val().trim()
        $("#selectNamespace").find('option').remove();
        $("#selectNamespace").append('<option value="_all">所有</option>');
        $.get('/api/v1/cluster/' + cluster_id + '/namespaces', function (data) {
            for (let i in data.items) {
                $("#selectNamespace").append('<option value="' + data.items[i].metadata.name + '">' + data.items[i].metadata.name + '</option>');
            }
            if (namespace) {
                $('#selectNamespace').val(namespace)
            }
        });
    }

    // 检测集群、命名空间，任一选择变化，则重载页面
    $(".need-refresh-table").change(function () {
        console.log("need-refresh-table")
        let cluster_id = $('#selectCluster').val()
        // var namespace = $("#selectNamespace").find("option:selected").text().trim()
        let namespace = $("#selectNamespace").val()

        console.log(cluster_id, namespace)

        if (cluster_id > 0) {
            let url = '/cluster/' + type + '/?cluster_id=' + cluster_id
            if (namespace) {
                url += '&namespace=' + namespace
            } else {
                url += '&namespace=_all'
                $('#selectNamespace').val(namespace)
            }
            location.href = url
        }
    })

    //用于读取所选表行单元格数据（值）的代码。
    $("#example1").on('click', '.btn_restart', function () {
        //获得当前行
        let currentRow = $(this).closest("tr");
        let item_name = currentRow.find("td:eq(0)").html(); //获得当前行第一个表格单元格TD值
        let item_ns = currentRow.find("td:eq(1)").html(); //获得当前行第一个表格单元格TD值
        // let col3 = currentRow.find("td:eq(2)").html(); //获得当前行第一个表格单元格TD值
        // let data = col1 + "\n" + col2 + "\n" + col3;
        console.log(cluster_id, item_ns, item_name);

        let restart_url = '/api/v1/cluster/' + cluster_id + '/' + item_ns + '/' + type + '/' + item_name + '/restart'
        $.get(restart_url, function (data) {
            console.log(data)
            if (data == 'success') {
                bootbox.alert('重新部署成功', function () {
                    setTimeout(function () {
                        location.reload()
                    }, 250)
                });
            } else {
                bootbox.alert('重新部署失败')
            }
        })
    });


</script>

{% endblock %}